package com.hrbxlh.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.SourceActionImpl;


/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：SourceAction.java
* Description：成绩action类
* History：
* Date           Author               Desc
* 2017.3.29		  sy                   建立
* -------------------------------------------------------
*/

@Controller
public class SourceAction {
	
	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;
	
	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表（教师）页面。进页面，翻页，条件查询都是这个。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllSourceList", method = RequestMethod.GET)
	public ModelAndView getAllSourceList(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			/*模拟参数开始*/
			/*Map<String, Object> mapUse = new HashMap<String, Object>();
			mapUse.put("pageNow", 1);
			mapUse.put("pageSize", 10);
			jsonStr = mapper.writeValueAsString(mapUse);*/
			/*模拟参数结束*/
			
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取人员列表信息
			Map<String, Object> resultAllMap = sourceActionImpl.getAllSourceList(preParamMap,session);
			if(preParamMap.get("classId")!=null||preParamMap.get("courseId")!=null||preParamMap.get("classEndMark")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("classId", preParamMap.get("classId"));
				searchObejct.put("courseId", preParamMap.get("courseId"));
				searchObejct.put("classEndMark", preParamMap.get("classEndMark"));
				resultMap.put("searchObejct", searchObejct);
			}
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//返回值
			resultMap.put("memberList", resultAllMap.get("memberList"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("classList", resultAllMap.get("classList"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
		    //人员列表页面名称
			pageName = "pc/findSource";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转学生成绩列表页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**
	 * 导入学生成绩
	 * @param file
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/imStuSoruce", method=RequestMethod.POST)
	public ModelAndView imStuSoruce(@RequestParam("file") CommonsMultipartFile file, HttpServletResponse response, HttpServletRequest request,HttpSession session) throws Exception {
		 System.out.println("导入学生成绩");
		 String fileName =  file.getOriginalFilename();
		 String view ="";
		 String reJsonStr = "";
		 ObjectMapper mapper = new ObjectMapper();
		 Map<String,Object> map = new HashMap<String,Object>();
		String jstr="%7B%22pageNow%22:1,%22pageSize%22:10,%22classEndMark%22:0%7D";
		//日志信息
		Logger logger = Logger.getLogger(ClassAction.class.getName());
		 try{
			 
			  String path = request.getSession().getServletContext().getRealPath("/upload/" + fileName);// 存放位置
			  File destFile = new File(path);
			  System.out.println(destFile);
			  String file1 = String.valueOf(destFile);
			  FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			  boolean flag = sourceActionImpl.imStuSoruce(file1,session);
			  if(flag){
				  view = "redirect:/getAllSourceList?jsonStr="+jstr; 
			  }else{
				  map.put("errMsg", "数据填写不正确，导入学生成绩失败");
				  view = "public/pageerror";
			  }
			  
		 }catch(Exception e){
			e.printStackTrace();
			map.put("errMsg", "数据填写不正确，导入学生成绩失败");
			e.printStackTrace();
			logger.error("导入学生成绩", e);
			view = "public/pageerror";
			
		 }finally{
			reJsonStr = mapper.writeValueAsString(map);
			map.put("result", reJsonStr);
		 }

		 return new ModelAndView(view,map);
	}
	
	/**
	 * 
	 * @return 查询成绩设置。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getProWedith", method = RequestMethod.GET)
	public ModelAndView getProWedith(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			
			
			//获取成绩设置信息
			Map<String, Object> resultAllMap = sourceActionImpl.getProWedith(session);
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//返回值
			resultMap.put("sorceMap", resultAllMap.get("sorceMap"));
		    //人员列表页面名称
			pageName = "pc/sourceSet";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("成绩设置异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}

	/**
	 * @param request
	 * @param response
	 * @return  成绩设置。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addSorceSet", method = RequestMethod.POST)
	public void addSorceSet(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ClassAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		try {
			
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//成绩设置。
			Map<String,Object> map = sourceActionImpl.addSorceSet(paramMap,session);
			boolean resultFlag = (Boolean) map.get("flag");
			resultMark = (resultFlag) ? "success" : "fail";
			resultMap.put("result", resultMark);
			resultMap.put("errMsg", map.get("errMsg"));
		} catch (Exception e) {
			resultMap.put("errMsg", "设置失败");
			e.printStackTrace();
			logger.error("添加班级出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/**
	 * @return  学生成绩详情
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getStuSourceDetail", method = RequestMethod.GET)
	public ModelAndView getStuSourceDetail(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取成绩详情信息
			Map<String, Object> resultAllMap = sourceActionImpl.getStuSourceDetail(preParamMap,session);
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//返回值
			resultMap.put("detailMap", resultAllMap.get("detailMap"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
		    //人员列表页面名称
			pageName = "pc/sourceDetail";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转学生成绩详情页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**
	 * @param pageNow,pageSize(一般是10)，页数从1开始，第一页pageNow传1
	 * @return  学生成绩列表页面(学生)。
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getStuAllSourceList", method = RequestMethod.GET)
	public ModelAndView getStuAllSourceList(String jsonStr, HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(MemberAction.class.getName());
		try {
			/*模拟参数开始*/
			/*Map<String, Object> mapUse = new HashMap<String, Object>();
			mapUse.put("pageNow", 1);
			mapUse.put("pageSize", 10);
			jsonStr = mapper.writeValueAsString(mapUse);*/
			/*模拟参数结束*/
			
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			//获取人员列表信息
			Map<String, Object> resultAllMap = sourceActionImpl.getStuAllSourceList(preParamMap,session);
			if(preParamMap.get("classId")!=null||preParamMap.get("courseId")!=null){
				//搜素框赋值对象
				Map<String,Object> searchObejct = new HashMap<String,Object>();
				searchObejct.put("courseId", preParamMap.get("courseId"));
				resultMap.put("searchObejct", searchObejct);
			}
			//查询当前人的消息
			List<Map<String, Object>> noticeList = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			
			//返回值
			resultMap.put("memberList", resultAllMap.get("memberList"));
			resultMap.put("courseList", resultAllMap.get("courseList"));
			resultMap.put("totalPage", resultAllMap.get("totalPage"));
			resultMap.put("pageNow", resultAllMap.get("pageNow"));
			resultMap.put("pageSize", preParamMap.get("pageSize"));
		    //人员列表页面名称
			pageName = "pc/findStuSource";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转学生成绩列表页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
}
